package cn.weiyang.controller;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 下载文件控制层
 * Created by Administrator on 2017/7/27.
 */
@Controller
public class DownFileController {
    private Logger logger= LogManager.getLogger(UpFileController.class);
    @Value("${fileSaveDir}")
    private String fileSaveDir;
    @RequestMapping("/downfile")
    /*filename是文件的随机生成名字，realOriginalFilename是文件上传前的真实名字*/
    public void down(String filename, HttpServletResponse resp){
        resp.setContentType("application/octet-stream; charset=utf-8");
        // 处理中文文件名中文乱码问题
        try {
            String realOriginalFilename = Const.fileMap.get(filename);
            String aa = new String(realOriginalFilename.getBytes("utf-8"), "ISO-8859-1");
            resp.setHeader("Content-Disposition", "attachment; filename=" + aa);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        try {
            IOUtils.copy(new FileInputStream(new File(fileSaveDir, filename)), resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
